<template>
  <div
    class="dashboard"
    v-loading="loading"
    element-loading-text="数据加载中..."
    element-loading-background="rgba(255, 255, 255, 0.9)"
    element-loading-svg-view-box="-10, -10, 50, 50"
    :element-loading-svg="svg"
  >
    <div class="dashboard-top">
      <AssetOverview
        :data="dashboardData.assetOverview"
        :rental-data="dashboardData.rentalData"
        :contract-data="dashboardData.contractData"
        :vacancy-data="dashboardData.vacancyData"
        :topInfo="dashboardData.topInfo"
      />
    </div>
    <div class="dashboard-bottom">
      <div class="chart-row">
        <WarningTrend
          class="chart-item trend"
          :data="dashboardData.warningTrend"
        />
        <WarningAssetList
          class="chart-item asset-list"
          :data="dashboardData.warningAssetList"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import AssetOverview from "./components/AssetOverview3.vue";
import WarningTrend from "./components/WarningTrend.vue";
import WarningAssetList from "./components/WarningAssetList.vue";
import {
  getAssetOverview,
  getSpecAssetList,
  getWarningTrends,
  getAssetCountByType,
  getWarningAssetCountByType,
  getPriceCompareAnalysis,
  getNoFileCount,
} from "./services";

const loading = ref(true);
const dashboardData = ref({
  // 资产概览数据 - 所有数值默认为0
  assetOverview: {
    totalAssets: 0,
    vacantRate: "0%",
    rentalPriceCount: 0,
    contractCount: 0,
    emptyMonitorCount: 0,
    noContractRate: "0%",
    vacantTotal: 0,
  },
  // 三个图表的数据
  rentalData: [], // 价格比对预警数据
  contractData: [], // 合同合规预警数据
  vacancyData: [], // 空置监测预警数据
  // 预警趋势数据 - 暂无数据
  warningTrend: {
    dates: [],
    series: [],
  },
  // 预警资产列表 - 暂无数据
  warningAssetList: [],
  // 空置分布数据 - 暂无数据
  vacancyDistribution: [],

  // 资产类型统计数据 - 暂无数据
  topInfo: {
    left: [
      { name: "房屋", value: 0, key: "fw" },
      { name: "土地", value: 0, key: "td" },
      { name: "车位", value: 0, key: "cw" },
      { name: "其他", value: 0, key: "qt" },
    ],

    right: {
      ht: [
        { name: "房屋", value: 0, key: "fw" },
        { name: "土地", value: 0, key: "td" },
        { name: "车位", value: 0, key: "cw" },
        { name: "其他", value: 0, key: "qt" },
      ],

      kz: [
        { name: "房屋", value: 0, key: "fw" },
        { name: "土地", value: 0, key: "td" },
        { name: "车位", value: 0, key: "cw" },
        { name: "其他", value: 0, key: "qt" },
      ],

      price: [
        { name: "评估", value: 0, key: "pinggu" },
        { name: "线上", value: 0, key: "xianshang" },
        { name: "线下", value: 0, key: "xiaxian" },
      ],

      file: [
        { name: "招标", value: 0, key: "zb" },
        { name: "合同", value: 0, key: "ht" },
        { name: "评估", value: 0, key: "pg" },
      ],
    },
  },
});

// 自定义loading图标
const svg = `
  <path class="path" d="
    M 30 15
    L 28 17
    M 25.61 25.61
    A 15 15, 0, 0, 1, 15 30
    A 15 15, 0, 1, 1, 27.99 7.5
    L 15 15
  " style="stroke-width: 4px; fill: none"/>
`;

const fetchData = async () => {
  try {
    loading.value = true;

    // 并发请求所有接口
    const [
      overviewData,
      specAssetData,
      rentalTrend,
      contractTrend,
      vacancyTrend,
      warningTrendData,
      assetTypeCount,
      warningAssetCountByHt,
      warningAssetCountByKz,
      priceCompareAnalysis,
      fileMissingAnalysis,
    ] = await Promise.all([
      getAssetOverview(),
      getSpecAssetList(),
      getWarningTrends("价格比对"),
      getWarningTrends("合同合规"),
      getWarningTrends("空置"),
      getWarningTrends(),
      getAssetCountByType(),
      getWarningAssetCountByType("合同合规"),
      getWarningAssetCountByType("空置"),
      getPriceCompareAnalysis(),
      getNoFileCount(),
    ]);

    // 处理资产类型统计数据
    dashboardData.value.topInfo = {
      left: assetTypeCount?.data
        ? [
            {
              name: "房屋",
              value: parseInt(assetTypeCount.data.fw) || 0,
              key: "fw",
            },
            {
              name: "土地",
              value: parseInt(assetTypeCount.data.td) || 0,
              key: "td",
            },
            {
              name: "车位",
              value: parseInt(assetTypeCount.data.cw) || 0,
              key: "cw",
            },
            {
              name: "其他",
              value: parseInt(assetTypeCount.data.qt) || 0,
              key: "qt",
            },
          ]
        : [
            { name: "房屋", value: 0, key: "fw" },
            { name: "土地", value: 0, key: "td" },
            { name: "车位", value: 0, key: "cw" },
            { name: "其他", value: 0, key: "qt" },
          ],
    };

    // 处理合同合规/空置监测分析数据
    dashboardData.value.topInfo.right = {
      ht: warningAssetCountByHt?.data
        ? [
            {
              name: "房屋",
              value: parseInt(warningAssetCountByHt.data.fw) || 0,
              key: "fw",
            },
            {
              name: "土地",
              value: parseInt(warningAssetCountByHt.data.td) || 0,
              key: "td",
            },
            {
              name: "车位",
              value: parseInt(warningAssetCountByHt.data.cw) || 0,
              key: "cw",
            },
            {
              name: "其他",
              value: parseInt(warningAssetCountByHt.data.qt) || 0,
              key: "qt",
            },
          ]
        : [
            { name: "房屋", value: 0, key: "fw" },
            { name: "土地", value: 0, key: "td" },
            { name: "车位", value: 0, key: "cw" },
            { name: "其他", value: 0, key: "qt" },
          ],
      kz: warningAssetCountByKz?.data
        ? [
            {
              name: "房屋",
              value: parseInt(warningAssetCountByKz.data.fw) || 0,
              key: "fw",
            },
            {
              name: "土地",
              value: parseInt(warningAssetCountByKz.data.td) || 0,
              key: "td",
            },
            {
              name: "车位",
              value: parseInt(warningAssetCountByKz.data.cw) || 0,
              key: "cw",
            },
            {
              name: "其他",
              value: parseInt(warningAssetCountByKz.data.qt) || 0,
              key: "qt",
            },
          ]
        : [
            { name: "房屋", value: 0, key: "fw" },
            { name: "土地", value: 0, key: "td" },
            { name: "车位", value: 0, key: "cw" },
            { name: "其他", value: 0, key: "qt" },
          ],
    };
    // 处理价格比对分析数据
    dashboardData.value.topInfo.right.price = priceCompareAnalysis?.data
      ? [
          {
            name: "评估",
            value: parseInt(priceCompareAnalysis.data.pinggu) || 0,
            key: "pinggu",
          },
          {
            name: "线上",
            value: parseInt(priceCompareAnalysis.data.xianshang) || 0,
            key: "xianshang",
          },
          {
            name: "线下",
            value: parseInt(priceCompareAnalysis.data.xiaxian) || 0,
            key: "xiaxian",
          },
        ]
      : [
          { name: "评估", value: 0, key: "pinggu" },
          { name: "线上", value: 0, key: "xianshang" },
          { name: "线下", value: 0, key: "xiaxian" },
        ];

    // 处理文件缺失分析数据
    dashboardData.value.topInfo.right.file = fileMissingAnalysis?.data
      ? [
          {
            name: "招标",
            value: parseInt(fileMissingAnalysis.data.zb) || 0,
            key: "zb",
          },
          {
            name: "合同",
            value: parseInt(fileMissingAnalysis.data.ht) || 0,
            key: "ht",
          },
          {
            name: "评估",
            value: parseInt(fileMissingAnalysis.data.pg) || 0,
            key: "pg",
          },
        ]
      : [
          { name: "招标", value: 0, key: "zb" },
          { name: "合同", value: 0, key: "ht" },
          { name: "评估", value: 0, key: "pg" },
        ];

    // 分别处理三种预警数据
    const rentalData = (rentalTrend?.data || []).map((item) => ({
      date: item.date || item.month,
      count: item.count,
    }));

    const contractData = (contractTrend?.data || []).map((item) => ({
      date: item.date || item.month,
      count: item.count,
    }));

    const vacancyData = (vacancyTrend?.data || []).map((item) => ({
      date: item.date || item.month,
      count: item.count,
    }));

    // 处理预警趋势数据
    const processWarningTrendData = (data) => {
      // 获取所有日期
      const allDates = [
        ...new Set(data.map((item) => item.date || item.month)),
      ].sort();

      // 按预警类型分组数据
      const groupedData = {
        价格比对: [],
        合同合规: [],
        空置: [],
        无合同: [],
      };

      // 初始化每个类型的数据数组
      Object.keys(groupedData).forEach((type) => {
        groupedData[type] = allDates.map((date) => {
          const item = data.find(
            (d) => (d.date || d.month) === date && d.warning_type === type
          );
          return item ? item.count : 0;
        });
      });

      return {
        dates: allDates,
        series: [
          {
            name: "租金比对预警",
            data: groupedData["价格比对"],
            type: "line",
            yAxisIndex: 0,
          },
          {
            name: "合同合规预警",
            data: groupedData["合同合规"],
            type: "line",
            yAxisIndex: 0,
          },
          {
            name: "空置监测预警",
            data: groupedData["空置"],
            type: "line",
            yAxisIndex: 0,
          },
          {
            name: "无合同",
            data: groupedData["无合同"],
            type: "line",
            yAxisIndex: 1,
          },
        ],
      };
    };

    // 更新各个模块的数据
    dashboardData.value = {
      assetOverview: {
        ...(overviewData?.data || {
          totalAssets: 0,
          vacantRate: "0%",
          rentalPriceCount: 0,
          contractCount: 0,
          emptyMonitorCount: 0,
          noContractRate: "0%",
          vacantTotal: 0,
        }),
      },
      // 分别赋值三个图表的数据到顶层
      rentalData,
      contractData,
      vacancyData,
      warningAssetList: specAssetData?.rows || [],
      warningTrend: processWarningTrendData(warningTrendData?.data || []),
      vacancyDistribution: [],
      topInfo: dashboardData.value.topInfo,
    };

    console.log("Dashboard data=====:", dashboardData.value);
  } catch (error) {
    console.error("Failed to fetch dashboard data:", error);
    // 发生错误时重置数据
    dashboardData.value.rentalData = [];
    dashboardData.value.contractData = [];
    dashboardData.value.vacancyData = [];
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 24px;
  background: #f5f7fa;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: calc(100vh - 84px);
  .dashboard-top {
    min-height: 340px;
    display: flex;
    flex-direction: column;
    flex: 6;
  }
  .dashboard-bottom {
    flex: 4;
    min-height: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .chart-row {
    display: flex;
    gap: 12px;
    height: 100%;
    // height: calc(100vh - 290px);
    // min-height: 400px;

    .chart-item {
      flex: 1;
      height: 100%;
      min-width: 0;
      background: #fff;
      border-radius: 8px;
      // padding: 20px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }
  }

  .chart-item.trend {
    flex: 1;
    min-width: 0;
  }

  .chart-item.asset-list {
    flex: 1;
    min-width: 0;
  }

  :deep(.chart-container) {
    width: 100%;
    height: 100%;
  }

  // 自定义loading样式
  :deep(.el-loading-spinner) {
    .path {
      stroke: var(--el-color-primary);
      stroke-linecap: round;
      animation: dash 1.5s ease-in-out infinite;
    }

    .el-loading-text {
      color: var(--el-color-primary);
      font-size: 16px;
      margin: 3px 0;
    }
  }
}

@keyframes dash {
  0% {
    stroke-dasharray: 1, 150;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -35;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -124;
  }
}
</style>
